package utils

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
)

// PageVisit 访问 url
func PageVisit(url string) (page string, body []byte) {
	if url == "" {
		fmt.Println("url is nil,  crawler task is finished")
		os.Exit(0)
	}

	resp, err := http.Get(url)

	if err != nil {
		panic("request error")
	}

	defer resp.Body.Close()

	body, _ = ioutil.ReadAll(resp.Body)
	page = string(body)
	return
}

// CheckRegexp 正则检查
func CheckRegexp(cont string, reg string, style int) (result interface{}) {
	check := regexp.MustCompile(reg)

	switch style {
	case 0:
		result = check.FindString(cont)
	case 1:
		result = check.FindAllString(cont, -1)
	default:
		result = check.FindAll([]byte(cont), -1)
	}
	return
}

// CheckFile 检查文件的路径
func CheckFile(dir string, file string) os.FileInfo {
	list, _ := ioutil.ReadDir(dir)
	for _, info := range list {
		if info.Name() == file {
			return info
		}
	}
	return list[0]
}

// SaveFile 保存文件
func SaveFile(file string, cont string) {
	f, _ := os.OpenFile(file, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
	defer f.Close()

	// 写入文件形式1： io.WriteString()
	io.WriteString(f, cont)
}

// DelFirstText 删除文本的内容，按行处理
func DelFirstText(file string) {
	var text = ""
	f, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0666)
	files, _ := ioutil.ReadAll(f)

	var ss = strings.Split(string(files), "\n")
	for i := 1; i < len(ss)-1; i++ {
		text += ss[i] + "\n"
	}
	defer f.Close()

	// 写入文件形式2：ioutil.WriteFile()
	ioutil.WriteFile(file, []byte(text), 0666)
	fmt.Print("\n\n删除改地址 => " + ss[0])
}
